package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.model.RoadpoleEntity;
import com.hualude.roadsign.model.RoadsignEntity;
import com.hualude.roadsign.repository.*;
import com.hualude.roadsign.service.RoadSignManageService;
import com.hualude.roadsign.utils.FormatNumber;
import com.sun.media.sound.SoftTuning;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sound.midi.Soundbank;
import java.security.AlgorithmConstraints;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by shao-yikun on 2017/4/7.
 */
@Service
public class RoadSignManageServiceImpl implements RoadSignManageService {

    @Resource
    private RoadPoleRepository roadPoleRepository;

    @Resource
    private RoadSignRepository roadSignRepository;

    @Resource
    private SignfaultRepository signfaultRepository;

    @Resource
    private MaintenanceRepository maintenanceRepository;

    @Resource
    private RegionRepository regionRepository;

    @Resource
    private OrgRepository orgRepository;

    @Resource
    private HistoryRepository historyRepository;

    public DTResponseDto getRoadPoleCollect4DT(DTRequestDto dtRequestDto,
                                               Integer orgId,
                                               String actorIds,
                                               String startRoad,
                                               String endRoad,
                                               String roadName,
                                               String saveState) throws Exception {
        List<RoadpoleDto> roadpoleDtos = roadPoleRepository.getRoadPoleCollect4DT(
                dtRequestDto, orgId, actorIds, startRoad, endRoad, roadName, saveState);
        Integer count = roadPoleRepository.getCount4DT(
                orgId, actorIds, startRoad, endRoad, roadName, saveState, dtRequestDto.getSearch());
        return new DTResponseDto(dtRequestDto.getDraw(), count, count, roadpoleDtos);
    }

    @Transactional
    public Integer updateRoadPoleCollect(RoadpoleDto roadpoleDto) throws Exception {
        for (RoadsignEntity roadsignEntity :
                roadSignRepository.getRoadSignByRoadPoleId(roadpoleDto.getRoadPoleId())) {
            if (!roadsignEntity.getMainOrgId().equals(roadpoleDto.getMainOrgId())) {
                roadSignRepository.updateMainOrgIdByRoadPoleId(
                        roadpoleDto.getRoadPoleId(),
                        roadpoleDto.getMainOrgId(),
                        roadpoleDto.getModifierId());
            }

            if (!roadsignEntity.getRoadSignRegionId().equals(roadpoleDto.getRoadPoleRegionId())) {
                roadSignRepository.updateRoadSignRegionIdByRoadPoleId(
                        roadpoleDto.getRoadPoleId(),
                        roadpoleDto.getRoadPoleRegionId(),
                        roadpoleDto.getModifierId());
            }
        }

        roadPoleRepository.updateRoadPoleCollect(
                roadpoleDto.getRoadPoleId(),
                roadpoleDto.getArea(),
                roadpoleDto.getLongitude(),
                roadpoleDto.getLatitude(),
                roadpoleDto.getRoadName(),
                roadpoleDto.getStartRoad(),
                roadpoleDto.getEndRoad(),
                roadpoleDto.getMainOrgId(),
                roadpoleDto.getRoadPoleSecurity(),
                roadpoleDto.getRoadPoleBridge(),
                roadpoleDto.getRoadPoleShape(),
                roadpoleDto.getRoadPoleSize(),
                roadpoleDto.getRoadPolePic(),
                roadpoleDto.getRoadPoleRegionId(),
                roadpoleDto.getProjectNumber(),
                roadpoleDto.getModifierId());
        return roadpoleDto.getRoadPoleId();
    }

    @Transactional
    public Integer addRoadPoleCollect(RoadpoleDto roadpoleDto) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        roadpoleDto.setRoadPoleIsComplete(0);
        roadpoleDto.setRoadPoleCreateTime(df.format(new Date()));
        roadpoleDto.setLongitude(FormatNumber.resize(roadpoleDto.getLongitude()));
        roadpoleDto.setLatitude(FormatNumber.resize(roadpoleDto.getLatitude()));
        return roadPoleRepository.save(roadpoleDto.toBean()).getRoadPoleId();
    }

    @Transactional
    public Integer deleteRoadPoleCollect(String roadPoleIds) throws Exception {
        String[] roadPoleIdArray = roadPoleIds.split(",");
        Integer count = 0;
        for (Integer i = 0; i < roadPoleIdArray.length; i++) {
            count = roadSignRepository.getRoadSignCountByRoadPole(Integer.parseInt(roadPoleIdArray[i]));
            if (count == 0)
                roadPoleRepository.deleteRoadPoleCollect(Integer.parseInt(roadPoleIdArray[i]));
            else
                break;
        }
        return count;
    }

    public DTResponseDto getRoadSignCollect4DT(DTRequestDto dtRequestDto, Integer roadPoleId) throws Exception {
        List<RoadsignDto> roadsignDtos = roadSignRepository.getRoadSignCollect4DT(dtRequestDto, roadPoleId);
        Integer count = roadSignRepository.getCount4DT(roadPoleId);
        Integer state = 0;
        List<SignfaultDto> signfaultDto = new ArrayList<SignfaultDto>();
        for (RoadsignDto dto : roadsignDtos) {
            state = 0;
            signfaultDto = signfaultRepository.getCheckByRoadSignId(dto.getRoadSignId());
            if (signfaultDto.size() > 0) {
                int companyCheck = signfaultDto.get(0).getCompanyCheck(), mainCheck = signfaultDto.get(0).getMainCheck();
                if (companyCheck != -1 && companyCheck != 2 && mainCheck == 0)
                    state = 1;//上报中
                else if (companyCheck == -1 || mainCheck == -1)
                    state = 2;//被否定
                else if ((companyCheck == 1 && mainCheck == 1) || companyCheck == 2) {
                    if (maintenanceRepository.getMaintenanceStatusByRoadSignId(dto.getRoadSignId()) != 2)
                        state = 3;//维修中
                }
            }
            dto.setReportState(state);
        }

        return new DTResponseDto(dtRequestDto.getDraw(), count, count, roadsignDtos);
    }

    public List<RoadsignDto> getRoadSignCollect(Integer roadPoleId) throws Exception {
        List<RoadsignDto> roadsignDtos = roadSignRepository.getRoadSignCollect(roadPoleId);
        Integer state = 0;
        List<SignfaultDto> signfaultDto = new ArrayList<SignfaultDto>();
        for (RoadsignDto dto : roadsignDtos) {
            state = 0;
            signfaultDto = signfaultRepository.getCheckByRoadSignId(dto.getRoadSignId());
            if (signfaultDto.size() > 0) {
                int companyCheck = signfaultDto.get(0).getCompanyCheck(), mainCheck = signfaultDto.get(0).getMainCheck();
                if (companyCheck != -1 && companyCheck != 2 && mainCheck == 0)
                    state = 1;//上报中
                if (companyCheck == -1 || mainCheck == -1)
                    state = 2;//被否定
                if ((companyCheck == 1 && mainCheck == 1) || companyCheck == 2) {
                    if (maintenanceRepository.getMaintenanceStatusByRoadSignId(dto.getRoadSignId()) != 2)
                        state = 3;//维修中
                }
            }
            dto.setReportState(state);
        }
        return roadsignDtos;
    }

    @Transactional
    public Integer updateRoadSignCollect(RoadsignDto roadsignDto) throws Exception {
        roadPoleRepository.setRoadPoleIsComplete(
                roadsignDto.getRoadPoleId(), roadsignDto.getModifierId());
        return roadSignRepository.updateRoadSignCollect(
                roadsignDto.getRoadSignId(),
                roadsignDto.getRoadSignDirection(),
                roadsignDto.getRoadSignType(),
                roadsignDto.getRoadSignMeaning(),
                roadsignDto.getRoadSignShape(),
                roadsignDto.getRoadSignSize(),
                roadsignDto.getRoadSignPic(),
                roadsignDto.getRoadSignMaterial(),
                roadsignDto.getRoadSignInstallType(),
                roadsignDto.getRoadSignFixed(),
                roadsignDto.getRoadSignSecurity(),
                roadsignDto.getRoadSignBug(),
                roadsignDto.getRoadSignRemark(),
                roadsignDto.getRoadSignLight(),
                roadsignDto.getEnvironment(),
                roadsignDto.getDefectsLiabilityPeriod(),
                roadsignDto.getServiceLife(),
                roadsignDto.getInstallOrg(),
                roadsignDto.getRoadSignInstallTime(),
                roadsignDto.getModifierId());
    }

    @Transactional
    public Integer addRoadSignCollect(RoadsignDto roadsignDto) throws Exception {
        roadPoleRepository.setRoadPoleIsComplete(
                roadsignDto.getRoadPoleId(), roadsignDto.getCreateUserId());
        roadsignDto.setRoadSignIsComplete(0);
        return roadSignRepository.save(roadsignDto.toBean()).getRoadSignId();
    }

    @Transactional
    public Integer deleteRoadSignCollect(String roadSignIds) throws Exception {
        String[] roadSignIdArray = roadSignIds.split(",");
        Integer i;
        for (i = 0; i < roadSignIdArray.length; i++) {
            Integer t = Integer.parseInt(roadSignIdArray[i]);
            signfaultRepository.deleteSignfaultByRoadSignId(t);
            maintenanceRepository.deleteMaintenanceByRoadSignId(t);
            roadSignRepository.deleteRoadSignCollect(t);
        }
        return i;
    }

    public RoadpoleEntity getRoadPoleByRoadPoleId(Integer roadPoleId) throws Exception {
        return roadPoleRepository.getRoadPoleByRoadPoleId(roadPoleId);
    }

    public List<RoadsignDto> getSignByRoadPoleId(Integer roadPoleId) throws Exception {
        List<RoadsignDto> roadsignDtos = roadSignRepository.getSignByRoadPoleId(roadPoleId);
        Integer state;
        List<SignfaultDto> signfaultDto;
        for (RoadsignDto dto : roadsignDtos) {
            state = 0;
            signfaultDto = signfaultRepository.getCheckByRoadSignId(dto.getRoadSignId());
            if (signfaultDto.size() > 0) {
                int companyCheck = signfaultDto.get(0).getCompanyCheck(), mainCheck = signfaultDto.get(0).getMainCheck();
                if (companyCheck != -1 && mainCheck == 0)
                    state = 1;//上报中
                else if (companyCheck == -1 || mainCheck == -1)
                    state = 2;//被否定
                else if (companyCheck == 1 && mainCheck == 1) {
                    if (maintenanceRepository.getMaintenanceStatusByRoadSignId(dto.getRoadSignId()) != 2)
                        state = 3;//维修中
                }
            }
            dto.setReportState(state);
        }
        return roadsignDtos;
    }

    public List<RoadpoleDto> getCoordinateByOrgId(Integer orgId,
                                                  String actorIds,
                                                  double neLongitude,
                                                  double neLatitude,
                                                  double swLongitude,
                                                  double swLatitude) throws Exception {
        return roadPoleRepository.getCoordinateByOrgId(orgId, actorIds, neLongitude, neLatitude, swLongitude, swLatitude);
    }


    public List<RegionDto> getRegion4Select(Integer pId) throws Exception {
        List<RegionDto> regionDtos;
        if (pId == 0)
            regionDtos = regionRepository.getProvince4Select();
        else
            regionDtos = regionRepository.getCity4Select(pId);
        return regionDtos;
    }

    public Integer getRegionIdByAddress(String province, String city, String area) throws Exception {
        Integer regionId = regionRepository.getProvinceRegionId(province);
        if (regionId != null) {
            regionId = regionRepository.getCityRegionId(regionId, city);
            if (regionId != null) {
                regionId = regionRepository.getAreaRegionId(regionId, area);
            }
        }
        return regionId;
    }

    public List<String> getRoadByRoadName(String roadName, Integer actorId, Integer orgId) throws Exception {
        return roadPoleRepository.getRoadByRoadName(roadName, actorId, orgId);
    }

    public List<String> getSectionByRoadName(String roadName, Integer actorId, Integer orgId) throws Exception {
        return roadPoleRepository.getSectionByRoadName(roadName, actorId, orgId);
    }

    public List<RoadpoleDto> getRoadPoleBySearch(Integer orgId, String actorIds, String strSearch, Integer mCount, Integer mySize) throws Exception {
        return roadPoleRepository.getRoadPoleBySearch(orgId, actorIds, strSearch, mCount, mySize);
    }

    public DTResponseDto getRoadPole2Report4DT(DTRequestDto dtRequestDto, Integer orgId, Integer userId, String startRoad,
                                               String endRoad, Integer actorId) throws Exception {
        if (actorId == 1 || actorId == 6) {
            List<RoadpoleDto> roadpoleDtos = roadPoleRepository.getRoadPole2Report4DT(dtRequestDto, orgId, actorId, startRoad, endRoad);
            Integer count = roadPoleRepository.getRoadPole2ReportCount4DT(dtRequestDto.getSearch(), orgId, actorId);
            return new DTResponseDto(dtRequestDto.getDraw(), count, count, roadpoleDtos);
        } else {
            return new DTResponseDto(dtRequestDto.getDraw(), 0, 0, "");
        }
    }

    @Transactional
    public Integer setRoadPoleMainOrg(String roadPoleIds, Integer mainOrgId) throws Exception {
        String[] roadPoleId = roadPoleIds.split(",");
        for (String rpId : roadPoleId)
            roadPoleRepository.setRoadPoleMainOrg(Integer.parseInt(rpId), mainOrgId);
        return 1;
    }

    public RoadsignDto getRoadSignByRoadSignId(Integer roadSignId) throws Exception {
        RoadsignDto roadsignDto = roadSignRepository.getRoadSignByRoadSignId(roadSignId);
        roadsignDto.setMainOrgName(orgRepository.getMainOrgName(roadsignDto.getMainOrgId()));
        roadsignDto.setOrgName(orgRepository.getMainOrgName(roadsignDto.getOrgId()));
        Integer state = 0;
        List<SignfaultDto> signfaultDto = signfaultRepository.getCheckByRoadSignId(roadsignDto.getRoadSignId());
        if (signfaultDto.size() > 0) {
            int companyCheck = signfaultDto.get(0).getCompanyCheck(), mainCheck = signfaultDto.get(0).getMainCheck();
            if (companyCheck != -1 && mainCheck == 0)
                state = 1;//上报中
            else if (companyCheck == -1 || mainCheck == -1)
                state = 2;//被否定
            else if (companyCheck == 1 && mainCheck == 1) {
                if (maintenanceRepository.getMaintenanceStatusByRoadSignId(roadsignDto.getRoadSignId()) != 2)
                    state = 3;//维修中
            }
        }
        roadsignDto.setReportState(state);
        return roadsignDto;
    }

    public List<String> getRoadByOrgId(Integer orgId, String city) throws Exception {
        if (city == null || city.equals("") || city.equals("全部"))
            return roadPoleRepository.getRoadByOrgId(orgId);
        else
            return roadPoleRepository.getRoadByOrgId2(orgId, city);
    }

    public List<String> getCityByOrgId(Integer orgId) throws Exception {
        return roadPoleRepository.getCityByOrgId(orgId);
    }

    public List<RoadpoleDto> getRoadPoleByFiltrate(String roadName, String city, Integer orgId, String actorIds) throws Exception {
        return roadPoleRepository.getRoadPoleByFiltrate(roadName, city, orgId, actorIds);

    }

    public DTResponseDto getRoadPole4ReportDT(DTRequestDto dtRequestDto, Integer orgId, String actorIds, String startRoad,
                                              String endRoad, String roadName) throws Exception {
        String isSave = "";
        if (dtRequestDto.getSearch().equals("安全"))
            isSave = "0";
        else if (dtRequestDto.getSearch().equals("不安全"))
            isSave = "1";
        if (roadName.equals("") && startRoad.equals("") && endRoad.equals("")) {
            return new DTResponseDto(dtRequestDto.getDraw(), 0, 0, "");
        } else {
            List<RoadpoleDto> roadpoleDtos = roadPoleRepository.getRoadPole4ReportDT(dtRequestDto, orgId, actorIds, startRoad,
                    endRoad, roadName, isSave);
            Integer count = roadPoleRepository.getRoadPole4ReportCountDT(orgId, actorIds, startRoad, endRoad, roadName, isSave);
            return new DTResponseDto(dtRequestDto.getDraw(), count, count, roadpoleDtos);
        }
    }

    public DTResponseDto getHistory4DT(DTRequestDto dtRequestDto, Integer equipmentId, Integer equipmentType) throws Exception {
        List<HistoryDto> historyDtos = historyRepository.getHistory4DT(dtRequestDto, equipmentId, equipmentType);
        Integer count = historyRepository.getHistoryCount(equipmentId, equipmentType, dtRequestDto.getSearch());
        return new DTResponseDto(dtRequestDto.getDraw(), count, count, historyDtos);
    }

    public List<HistoryDto> getHistory4APP(Integer equipmentId,
                                           Integer equipmentType,
                                           Integer mCount,
                                           Integer mSize) throws Exception {
        return historyRepository.getHistory4APP(equipmentId, equipmentType, mCount, mSize);
    }

}
